package com.adee.gulimall.product.app;

import com.adee.gulimall.common.utils.PageUtils;
import com.adee.gulimall.util.utils.R;
import com.adee.gulimall.product.entity.SpuInfoEntity;
import com.adee.gulimall.product.service.SpuInfoService;
import com.adee.gulimall.product.vo.SpuSaveVo;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * spu信息
 *
 * @author adee
 * @email 609980188@qq.com
 * @date 2022-08-19 16:28:49
 */
@Slf4j
@RestController
@RequestMapping("product/spuinfo")
public class SpuInfoController {
    @Autowired
    private SpuInfoService spuInfoService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    //@Autowired
    RedissonClient redissonClient;

    /**
     * 列表
     */
    @RequestMapping("/list")
    // @RequiresPermissions("product:spuinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        // PageUtils page = spuInfoService.queryPage(params);
        PageUtils page = spuInfoService.queryPageByCondition(params);
        return R.ok().put("page", page);
    }


    /**
     * 查询商品spu信息
     * 使用redisson分布式锁
     * redission.lock()是阻塞式等待，默认锁的过期时间是30s。
     * 1. redission每个锁都会创建一个线程更新过期时间，每10s更新一次，更新为30s，所以不会因为业务操作耗时而导致锁自动删除；
     * 2. 不会因为客户端宕机而导致死锁，因为锁设置了过期时间。
     * 注意：锁粒度要合理，此处只需给具体id的spu加锁，而不是给整个spu加锁，锁粒度越大，延迟越高，因此需要尽可能小粒度加锁。
     */
    @RequestMapping("/info/{id}")
    // @RequiresPermissions("product:spuinfo:info")
    public R info(@PathVariable("id") Long id){
        Gson gson = new Gson();
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String spuKey = "spuInfo:"+id;
        String spuInfoCache = ops.get(spuKey);
        if(spuInfoCache == null) {
            String lockName = "lock:spu:" + spuKey;
            RLock lock = redissonClient.getLock(lockName);
            lock.lock();
            try {
                // 再次取缓存
                spuInfoCache = ops.get(spuKey);
                if(spuInfoCache == null) {
                    SpuInfoEntity spuInfo = spuInfoService.getById(id);
                    if(spuInfo == null) {
                        ops.set(spuKey, "", 30, TimeUnit.SECONDS);
                    } else {
                        ops.set(spuKey, gson.toJson(spuInfo));
                    }
                }
                TimeUnit.SECONDS.sleep(50);
            } catch (Exception e) {
                log.error("redissonClient加锁操作中异常，lockName:{}", lockName, e);
            } finally {
                lock.unlock();
            }
        }

        SpuInfoEntity spuInfoEntity = gson.fromJson(spuInfoCache, SpuInfoEntity.class);
        return R.ok().put("spuInfo", spuInfoEntity);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    // @RequiresPermissions("product:spuinfo:save")
    public R save(@RequestBody SpuSaveVo vo){
		spuInfoService.saveSpuInfo(vo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    // @RequiresPermissions("product:spuinfo:update")
    public R update(@RequestBody SpuInfoEntity spuInfo){
		spuInfoService.updateById(spuInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    // @RequiresPermissions("product:spuinfo:delete")
    public R delete(@RequestBody Long[] ids){
		spuInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 商品上架
     */
    @RequestMapping("/{spuId}/up")
    // @RequiresPermissions("product:spuinfo:update")
    public R spuInfo(@PathVariable("spuId") Long spuId){
        spuInfoService.spuUp(spuId);

        return R.ok();
    }

}
